import os
import subprocess

# Source ROS环境
ros_setup_path = "/opt/ros/noetic/setup.bash"
mavros_ws_setup_path = "/home/user/your_workspace/devel/setup.bash"

# 动态 source setup.bash
command = ['bash', '-c', f"source {ros_setup_path} && source {mavros_ws_setup_path} && env"]
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in proc.stdout:
    (key, _, value) = line.decode("utf-8").partition("=")
    os.environ[key] = value.strip()

import rospy
from std_msgs.msg import String

# 后续ROS相关代码
def callback(data):
    rospy.loginfo("I heard %s", data.data)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("chatter", String, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()

